{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<table width=\"100%\">\n",
    "<tr style=\"background-color: red;\"><td><font color=\"white\">SimpleITK conventions:</font></td></tr>\n",
    "<tr><td>\n",
    "<ul>\n",
    "<li> SimpleITK indexes are zero based, except for the slicing operator which conforms with R conventions and is one based.</li>\n",
    "<li>Points are represented by vector-like data types: vector, array, list.</li>\n",
    "<li>Matrices are represented by vector-like data types in row major order.</li>\n",
    "<li>Initializing the DisplacementFieldTransform using an image requires that the image's pixel type be sitk.sitkVectorFloat64</li>\n",
    "<li>Initializing the DisplacementFieldTransform using an image will \"clear out\" your image (your alias to the image will point to an empty, zero sized, image).</li>\n",
    "</ul>\n",
    "</td></tr>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# SimpleITK Transformation Types\n",
    "This notebook introduces the transformation types supported by SimpleITK and illustrates how to \"promote\" transformations from a lower to higher parameter space (e.g. 3D translation to 3D rigid).  \n",
    "\n",
    "<table width=\"100%\">\n",
    "<tr><td><a href=\"http://www.itk.org/Doxygen/html/classitk_1_1TranslationTransform.html\">TranslationTransform</a></td><td>2D or 3D, translation</td></tr>\n",
    "  <tr><td><a href=\"http://www.itk.org/Doxygen/html/classitk_1_1VersorTransform.html\">VersorTransform</a></td><td>3D, rotation represented by a versor</td></tr>\n",
    "  <tr><td><a href=\"http://www.itk.org/Doxygen/html/classitk_1_1VersorRigid3DTransform.html\">VersorRigid3DTransform</a></td><td>3D, rigid transformation with rotation represented by a versor</td></tr>\n",
    "  <tr><td><a href=\"http://www.itk.org/Doxygen/html/classitk_1_1Euler2DTransform.html\">Euler2DTransform</a></td><td>2D, rigid transformation with rotation represented by a Euler angle</td></tr>\n",
    "  <tr><td><a href=\"http://www.itk.org/Doxygen/html/classitk_1_1Euler3DTransform.html\">Euler3DTransform</a></td><td>3D, rigid transformation with rotation represented by Euler angles</td></tr>\n",
    "  <tr><td><a href=\"http://www.itk.org/Doxygen/html/classitk_1_1Similarity2DTransform.html\">Similarity2DTransform</a></td><td>2D, composition of isotropic scaling and rigid transformation with rotation represented by a Euler angle</td></tr>\n",
    "  <tr><td><a href=\"http://www.itk.org/Doxygen/html/classitk_1_1Similarity3DTransform.html\">Similarity3DTransform</a></td><td>3D, composition of isotropic scaling and rigid transformation with rotation represented by a versor</td></tr>\n",
    "  <tr><td><a href=\"http://www.itk.org/Doxygen/html/classitk_1_1ScaleTransform.html\">ScaleTransform</a></td><td>2D or 3D, anisotropic scaling</td></tr>\n",
    "  <tr><td><a href=\"http://www.itk.org/Doxygen/html/classitk_1_1ScaleVersor3DTransform.html\">ScaleVersor3DTransform</a></td><td>3D, rigid transformation and anisotropic scale is <bf>added</bf> to the rotation matrix part (not composed as one would expect)</td></tr>\n",
    "  <tr><td><a href=\"http://www.itk.org/Doxygen/html/classitk_1_1ScaleSkewVersor3DTransform.html\">ScaleSkewVersor3DTransform</a></td><td>3D, rigid transformation with anisotropic scale and skew matrices <bf>added</bf> to the rotation matrix part (not composed as one would expect)</td></tr>\n",
    "  <tr><td><a href=\"http://www.itk.org/Doxygen/html/classitk_1_1AffineTransform.html\">AffineTransform</a></td><td>2D or 3D, affine transformation.</td></tr>\n",
    "  <tr><td><a href=\"http://www.itk.org/Doxygen/html/classitk_1_1BSplineTransform.html\">BSplineTransform</a></td><td>2D or 3D, deformable transformation represented by a sparse regular grid of control points. </td></tr>\n",
    "  <tr><td><a href=\"http://www.itk.org/Doxygen/html/classitk_1_1DisplacementFieldTransform.html\">DisplacementFieldTransform</a></td><td>2D or 3D, deformable transformation represented as a dense regular grid of vectors.</td></tr>\n",
    "  <tr><td><a href=\"http://www.itk.org/SimpleITKDoxygen/html/classitk_1_1simple_1_1Transform.html\">Transform</a></td>\n",
    "  <td>A generic transformation. Can represent any of the SimpleITK transformations, and a <b>composite transformation</b> (stack of transformations concatenated via composition, last added, first applied). </td></tr>\n",
    "  </table>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "library(SimpleITK)\n",
    "\n",
    "library(scatterplot3d)\n",
    "\n",
    "OUTPUT_DIR <- \"Output\"\n",
    "\n",
    "print(Version())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Points in SimpleITK"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Utility functions\n",
    "\n",
    "A number of functions that deal with point data in a uniform manner."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Format a point for printing, based on specified precision with trailing zeros. Uniform printing for vector-like data \n",
    "# (vector, array, list).\n",
    "# @param point (vector-like): nD point with floating point coordinates.\n",
    "# @param precision (int): Number of digits after the decimal point.\n",
    "# @return: String representation of the given point \"xx.xxx yy.yyy zz.zzz...\".\n",
    "point2str <- function(point, precision=1)\n",
    "{\n",
    "    precision_str <- sprintf(\"%%.%df\",precision)\n",
    "    return(paste(lapply(point, function(x) sprintf(precision_str, x)), collapse=\", \"))\n",
    "}\n",
    "                         \n",
    "                         \n",
    "# Generate random (uniform withing bounds) nD point cloud. Dimension is based on the number of pairs in the \n",
    "# bounds input.\n",
    "# @param bounds (list(vector-like)): List where each vector defines the coordinate bounds.\n",
    "# @param num_points (int): Number of points to generate.\n",
    "# @return (matrix): Matrix whose columns are the set of points.                         \n",
    "uniform_random_points <- function(bounds, num_points)\n",
    "{\n",
    "    return(t(sapply(bounds, function(bnd,n=num_points) runif(n, min(bnd),max(bnd)))))\n",
    "}\n",
    "                                 \n",
    "\n",
    "# Distances between points transformed by the given transformation and their\n",
    "# location in another coordinate system. When the points are only used to evaluate\n",
    "# registration accuracy (not used in the registration) this is the target registration\n",
    "# error (TRE).\n",
    "# @param tx (SimpleITK transformation): Transformation applied to the points in point_list\n",
    "# @param point_data (matrix): Matrix whose columns are points which we transform using tx.\n",
    "# @param reference_point_data (matrix): Matrix whose columns are points to which we compare \n",
    "#                                       the transformed point data.                                              \n",
    "# @return (vector): Distances between the transformed points and the reference points.\n",
    "target_registration_errors <- function(tx, point_data, reference_point_data)\n",
    "{\n",
    "    transformed_points_mat <- apply(point_data, MARGIN=2, tx$TransformPoint)\n",
    "    return (sqrt(colSums((transformed_points_mat - reference_point_data)^2)))\n",
    "}\n",
    "                                 \n",
    "                                 \n",
    "# Check whether two transformations are \"equivalent\" in an arbitrary spatial region \n",
    "# either 3D or 2D, [x=(-10,10), y=(-100,100), z=(-1000,1000)]. This is just a sanity check, \n",
    "# as we are just looking at the effect of the transformations on a random set of points in\n",
    "# the region.\n",
    "print_transformation_differences <- function(tx1, tx2)\n",
    "{\n",
    "    if (tx1$GetDimension()==2 && tx2$GetDimension()==2)\n",
    "    {\n",
    "        bounds <- list(c(-10,10), c(-100,100))\n",
    "    }\n",
    "    else if(tx1$GetDimension()==3 && tx2$GetDimension()==3)\n",
    "    {\n",
    "        bounds <- list(c(-10,10), c(-100,100), c(-1000,1000))\n",
    "    }\n",
    "    else\n",
    "        stop('Transformation dimensions mismatch, or unsupported transformation dimensionality')\n",
    "    num_points <- 10\n",
    "    point_data <- uniform_random_points(bounds, num_points)\n",
    "    tx1_point_data <- apply(point_data, MARGIN=2, tx1$TransformPoint)\n",
    "    differences <- target_registration_errors(tx2, point_data, tx1_point_data)\n",
    "    cat(tx1$GetName(), \"-\", tx2$GetName(), \":\\tminDifference: \", \n",
    "        toString(min(differences)), \" maxDifference: \",toString(max(differences))) \n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In SimpleITK points can be represented by any vector-like data type. In R these include vector, array, and list. In general R will treat these data types differently, as illustrated by the print function below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# SimpleITK points represented by vector-like data structures. \n",
    "point_vector <- c(9.0, 10.531, 11.8341)\n",
    "point_array <- array(c(9.0, 10.531, 11.8341),dim=c(1,3)) \n",
    "point_list <- list(9.0, 10.531, 11.8341)\n",
    "\n",
    "print(point_vector)\n",
    "print(point_array)\n",
    "print(point_list)\n",
    "\n",
    "# Uniform printing with specified precision.\n",
    "precision <- 2\n",
    "print(point2str(point_vector, precision))\n",
    "print(point2str(point_array, precision))\n",
    "print(point2str(point_list, precision))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Global Transformations\n",
    "All global transformations <i>except translation</i> are of the form:\n",
    "$$T(\\mathbf{x}) = A(\\mathbf{x}-\\mathbf{c}) + \\mathbf{t} + \\mathbf{c}$$\n",
    "\n",
    "In ITK speak (when printing your transformation):\n",
    "<ul>\n",
    "<li>Matrix: the matrix $A$</li>\n",
    "<li>Center: the point $\\mathbf{c}$</li>\n",
    "<li>Translation: the vector $\\mathbf{t}$</li>\n",
    "<li>Offset: $\\mathbf{t} + \\mathbf{c} - A\\mathbf{c}$</li>\n",
    "</ul>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## TranslationTransform"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# A 3D translation. Note that you need to specify the dimensionality, as the sitk TranslationTransform \n",
    "# represents both 2D and 3D translations.\n",
    "dimension <- 3        \n",
    "offset <- c(1,2,3) # offset can be any vector-like data  \n",
    "translation <- TranslationTransform(dimension, offset)\n",
    "print(translation)\n",
    "translation$GetOffset()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Transform a point and use the inverse transformation to get the original back.\n",
    "point <- c(10, 11, 12)\n",
    "transformed_point <- translation$TransformPoint(point)\n",
    "translation_inverse <- translation$GetInverse()\n",
    "cat(paste0(\"original point: \", point2str(point), \"\\n\",\n",
    "          \"transformed point: \", point2str(transformed_point), \"\\n\",\n",
    "          \"back to original: \", point2str(translation_inverse$TransformPoint(transformed_point))))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## Euler2DTransform"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "point <- c(10, 11)\n",
    "rotation2D <- Euler2DTransform()\n",
    "rotation2D$SetTranslation(c(7.2, 8.4))\n",
    "rotation2D$SetAngle(pi/2.0)\n",
    "cat(paste0(\"original point: \", point2str(point), \"\\n\",\n",
    "      \"transformed point: \", point2str(rotation2D$TransformPoint(point)),\"\\n\"))\n",
    "\n",
    "# Change the center of rotation so that it coincides with the point we want to\n",
    "# transform, why is this a unique configuration?\n",
    "rotation2D$SetCenter(point)\n",
    "cat(paste0(\"original point: \", point2str(point), \"\\n\",\n",
    "          \"transformed point: \", point2str(rotation2D$TransformPoint(point)),\"\\n\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## VersorTransform"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Rotation only, parametrized by Versor (vector part of unit quaternion),\n",
    "# quaternion defined by rotation of theta around axis n: \n",
    "#  q = [n*sin(theta/2), cos(theta/2)]\n",
    "               \n",
    "# 180 degree rotation around z axis\n",
    "\n",
    "# Use a versor:\n",
    "rotation1 <- VersorTransform(c(0,0,1,0))\n",
    "\n",
    "# Use axis-angle:\n",
    "rotation2 <- VersorTransform(c(0,0,1), pi)\n",
    "\n",
    "# Use a matrix:\n",
    "rotation3 <- VersorTransform()\n",
    "rotation3$SetMatrix(c(-1, 0, 0, 0, -1, 0, 0, 0, 1))\n",
    "\n",
    "point <- c(10, 100, 1000)\n",
    "\n",
    "p1 <- rotation1$TransformPoint(point)\n",
    "p2 <- rotation2$TransformPoint(point)\n",
    "p3 <- rotation3$TransformPoint(point)\n",
    "\n",
    "cat(paste0(\"Points after transformation:\\np1=\", point2str(p1,15), \n",
    "      \"\\np2=\", point2str(p2,15),\"\\np3=\", point2str(p3,15)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We applied the \"same\" transformation to the same point, so why are the results slightly different for the second initialization method?\n",
    "  \n",
    "This is where theory meets practice. Using the axis-angle initialization method involves trigonometric functions which on a fixed precision machine lead to these slight differences. In many cases this is not an issue, but it is something to remember. From here on we will sweep it under the rug (printing with a more reasonable precision). "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Translation to Rigid [3D]\n",
    "Copy the translational component."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "dimension <- 3        \n",
    "trans <- c(1,2,3) \n",
    "translation <- TranslationTransform(dimension, trans)\n",
    "\n",
    "# Only need to copy the translational component.\n",
    "rigid_euler <- Euler3DTransform()\n",
    "rigid_euler$SetTranslation(translation$GetOffset()) \n",
    "rigid_versor <- VersorRigid3DTransform()\n",
    "rigid_versor$SetTranslation(translation$GetOffset())\n",
    "\n",
    "# Sanity check to make sure the transformations are equivalent.\n",
    "bounds <- list(c(-10,10), c(-100,100), c(-1000,1000))\n",
    "num_points <- 10\n",
    "point_data <- uniform_random_points(bounds, num_points)\n",
    "transformed_point_data <- apply(point_data, MARGIN=2, translation$TransformPoint) \n",
    "\n",
    "# Draw the original and transformed points.\n",
    "all_data <- cbind(point_data, transformed_point_data)\n",
    "xbnd <- range(all_data[1,])\n",
    "ybnd <- range(all_data[2,])\n",
    "zbnd <- range(all_data[3,])\n",
    "\n",
    "s3d <- scatterplot3d(t(point_data), color = \"blue\", pch = 19, xlab='', ylab='', zlab='',\n",
    "                     xlim=xbnd, ylim=ybnd, zlim=zbnd)\n",
    "s3d$points3d(t(transformed_point_data), col = \"red\", pch = 17)\n",
    "legend(\"topleft\", col= c(\"blue\", \"red\"), pch=c(19,17), legend = c(\"Original points\", \"Transformed points\"))\n",
    "\n",
    "euler_errors <- target_registration_errors(rigid_euler, point_data, transformed_point_data)\n",
    "versor_errors <- target_registration_errors(rigid_versor, point_data, transformed_point_data)\n",
    "\n",
    "cat(paste0(\"Euler\\tminError:\", point2str(min(euler_errors)),\" maxError: \", point2str(max(euler_errors)),\"\\n\"))\n",
    "cat(paste0(\"Versor\\tminError:\", point2str(min(versor_errors)),\" maxError: \", point2str(max(versor_errors)),\"\\n\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## Rotation to Rigid [3D]\n",
    "Copy the matrix or versor and <b>center of rotation</b>."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "rotationCenter <- c(10, 10, 10)\n",
    "rotation <- VersorTransform(c(0,0,1,0), rotationCenter)\n",
    "\n",
    "rigid_euler <- Euler3DTransform()\n",
    "rigid_euler$SetMatrix(rotation$GetMatrix())\n",
    "rigid_euler$SetCenter(rotation$GetCenter())\n",
    "\n",
    "rigid_versor <- VersorRigid3DTransform()\n",
    "rigid_versor$SetRotation(rotation$GetVersor())\n",
    "#rigid_versor.SetCenter(rotation.GetCenter()) #intentional error\n",
    "\n",
    "# Sanity check to make sure the transformations are equivalent.\n",
    "bounds <- list(c(-10,10),c(-100,100), c(-1000,1000))\n",
    "num_points = 10\n",
    "point_data = uniform_random_points(bounds, num_points)\n",
    "transformed_point_data <- apply(point_data, MARGIN=2, rotation$TransformPoint) \n",
    "    \n",
    "euler_errors = target_registration_errors(rigid_euler, point_data, transformed_point_data)\n",
    "versor_errors = target_registration_errors(rigid_versor, point_data, transformed_point_data)\n",
    "\n",
    "# Draw the points transformed by the original transformation and after transformation\n",
    "# using the incorrect transformation, illustrate the effect of center of rotation.\n",
    "incorrect_transformed_point_data <- apply(point_data, 2, rigid_versor$TransformPoint) \n",
    "\n",
    "all_data <- cbind(transformed_point_data, incorrect_transformed_point_data)\n",
    "xbnd <- range(all_data[1,])\n",
    "ybnd <- range(all_data[2,])\n",
    "zbnd <- range(all_data[3,])\n",
    "s3d <- scatterplot3d(t(transformed_point_data), color = \"blue\", pch = 19, xlab='', ylab='', zlab='',\n",
    "                     xlim=xbnd, ylim=ybnd, zlim=zbnd)\n",
    "s3d$points3d(t(incorrect_transformed_point_data), col = \"red\", pch = 17)\n",
    "legend(\"topleft\", col= c(\"blue\", \"red\"), pch=c(19,17), legend = c(\"Original points\", \"Transformed points\"))\n",
    "\n",
    "\n",
    "cat(paste0(\"Euler\\tminError:\", point2str(min(euler_errors)),\" maxError: \", point2str(max(euler_errors)),\"\\n\"))\n",
    "cat(paste0(\"Versor\\tminError:\", point2str(min(versor_errors)),\" maxError: \", point2str(max(versor_errors)),\"\\n\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## Similarity [2D]\n",
    "\n",
    "When the center of the similarity transformation is not at the origin the effect of the transformation is not what most of us expect. This is readily visible if we limit the transformation to scaling: $T(\\mathbf{x}) = s\\mathbf{x}-s\\mathbf{c} + \\mathbf{c}$. Changing the transformation's center results in scale + translation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 2D square centered on (0,0)\n",
    "points <- matrix(data=c(-1.0,-1.0, -1.0,1.0, 1.0,1.0, 1.0,-1.0), ncol=4, nrow=2) \n",
    "# Scale by 2 (center default is [0,0])\n",
    "similarity <- Similarity2DTransform();\n",
    "similarity$SetScale(2)\n",
    "\n",
    "scaled_points <- apply(points, MARGIN=2, similarity$TransformPoint) \n",
    "\n",
    "#Uncomment the following lines to change the transformations center and see what happens:\n",
    "#similarity$SetCenter(c(0,2))\n",
    "#scaled_points <- apply(points, 2, similarity$TransformPoint) \n",
    "\n",
    "plot(points[1,],points[2,], xlim=c(-10,10), ylim=c(-10,10), pch=19, col=\"blue\", xlab=\"\", ylab=\"\", las=1)\n",
    "points(scaled_points[1,], scaled_points[2,], col=\"red\", pch=17)\n",
    "legend('top', col= c(\"red\", \"blue\"), pch=c(17,19), legend = c(\"transformed points\", \"original points\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## Rigid to Similarity [3D]\n",
    "Copy the translation, center, and matrix or versor."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "rotation_center <- c(100, 100, 100)\n",
    "theta_x <- 0.0\n",
    "theta_y <- 0.0\n",
    "theta_z <- pi/2.0\n",
    "translation <- c(1,2,3)\n",
    "\n",
    "rigid_euler <- Euler3DTransform(rotation_center, theta_x, theta_y, theta_z, translation)\n",
    "\n",
    "similarity <- Similarity3DTransform()\n",
    "similarity$SetMatrix(rigid_euler$GetMatrix())\n",
    "similarity$SetTranslation(rigid_euler$GetTranslation())\n",
    "similarity$SetCenter(rigid_euler$GetCenter())\n",
    "\n",
    "# Apply the transformations to the same set of random points and compare the results\n",
    "# (see utility functions at top of notebook).\n",
    "print_transformation_differences(rigid_euler, similarity)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "## Similarity to Affine [3D]\n",
    "Copy the translation, center and matrix."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "rotation_center <- c(100, 100, 100)\n",
    "axis <- c(0,0,1)\n",
    "angle <- pi/2.0\n",
    "translation <- c(1,2,3)\n",
    "scale_factor <- 2.0\n",
    "similarity <- Similarity3DTransform(scale_factor, axis, angle, translation, rotation_center)\n",
    "\n",
    "affine <- AffineTransform(3)\n",
    "affine$SetMatrix(similarity$GetMatrix())\n",
    "affine$SetTranslation(similarity$GetTranslation())\n",
    "affine$SetCenter(similarity$GetCenter())\n",
    "\n",
    "# Apply the transformations to the same set of random points and compare the results\n",
    "# (see utility functions at top of notebook).\n",
    "print_transformation_differences(similarity, affine)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Scale Transform\n",
    "\n",
    "Just as the case was for the similarity transformation above, when the transformations center is not at the origin, instead of a pure anisotropic scaling we also have translation ($T(\\mathbf{x}) = \\mathbf{s}^T\\mathbf{x}-\\mathbf{s}^T\\mathbf{c} + \\mathbf{c}$)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 2D square centered on (0,0).\n",
    "points <- matrix(data=c(-1.0,-1.0, -1.0,1.0, 1.0,1.0, 1.0,-1.0), ncol=4, nrow=2) \n",
    "\n",
    "# Scale by half in x and 2 in y.\n",
    "scale <- ScaleTransform(2, c(0.5,2));\n",
    "\n",
    "scaled_points <- apply(points, 2, scale$TransformPoint) \n",
    "\n",
    "#Uncomment the following lines to change the transformations center and see what happens:\n",
    "#scale$SetCenter(c(0,2))\n",
    "#scaled_points <- apply(points, 2, scale$TransformPoint) \n",
    "\n",
    "plot(points[1,],points[2,], xlim=c(-10,10), ylim=c(-10,10), pch=19, col=\"blue\", xlab=\"\", ylab=\"\", las=1)\n",
    "points(scaled_points[1,], scaled_points[2,], col=\"red\", pch=17)\n",
    "legend('top', col= c(\"red\", \"blue\"), pch=c(17,19), legend = c(\"transformed points\", \"original points\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Scale Versor\n",
    "\n",
    "This is not what you would expect from the name (composition of anisotropic scaling and rigid). This is:\n",
    "$$T(x) = (R+S)(\\mathbf{x}-\\mathbf{c}) + \\mathbf{t} + \\mathbf{c},\\;\\; \\textrm{where } S= \\left[\\begin{array}{ccc} s_0-1 & 0 & 0 \\\\ 0 & s_1-1 & 0 \\\\ 0 & 0 & s_2-1 \\end{array}\\right]$$ \n",
    "\n",
    "There is no natural way of \"promoting\" the similarity transformation to this transformation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "scales <- c(0.5,0.7,0.9)\n",
    "translation <- c(1,2,3)\n",
    "axis <- c(0,0,1)\n",
    "angle <- 0.0\n",
    "scale_versor <- ScaleVersor3DTransform(scales, axis, angle, translation)\n",
    "print(scale_versor)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Scale Skew Versor\n",
    "\n",
    "Again, not what you expect based on the name, this is not a composition of transformations. This is:\n",
    "$$T(x) = (R+S+K)(\\mathbf{x}-\\mathbf{c}) + \\mathbf{t} + \\mathbf{c},\\;\\; \\textrm{where } S = \\left[\\begin{array}{ccc} s_0-1 & 0 & 0 \\\\ 0 & s_1-1 & 0 \\\\ 0 & 0 & s_2-1 \\end{array}\\right]\\;\\; \\textrm{and } K = \\left[\\begin{array}{ccc} 0 & k_0 & k_1 \\\\ k_2 & 0 & k_3 \\\\ k_4 & k_5 & 0 \\end{array}\\right]$$ \n",
    "\n",
    "In practice this is an over-parametrized version of the affine transform, 15 (scale, skew, versor, translation) vs. 12 parameters (matrix, translation)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "scale <- c(2,2.1,3)\n",
    "skew <- 0:1/6.0:1 #six equally spaced values in[0,1], an arbitrary choice\n",
    "translation <- c(1,2,3)\n",
    "versor <- c(0,0,0,1.0)\n",
    "scale_skew_versor <- ScaleSkewVersor3DTransform(scale, skew, versor, translation)\n",
    "print(scale_skew_versor)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Bounded Transformations\n",
    "\n",
    "SimpleITK supports two types of bounded non-rigid transformations, BSplineTransform (sparse representation) and \tDisplacementFieldTransform (dense representation).\n",
    "\n",
    "Transforming a point that is outside the bounds will return the original point - identity transform."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "#\n",
    "# This function displays the effects of the deformable transformation on a grid of points by scaling the\n",
    "# initial displacements (either of control points for BSpline or the deformation field itself). It does\n",
    "# assume that all points are contained in the range(-2.5,-2.5), (2.5,2.5) - for display.\n",
    "#\n",
    "display_displacement_scaling_effect <- function(s, original_x_mat, original_y_mat, tx, original_control_point_displacements)\n",
    "{\n",
    "    if(tx$GetDimension()!=2)\n",
    "        stop('display_displacement_scaling_effect only works in 2D')\n",
    "\n",
    "    tx$SetParameters(s*original_control_point_displacements)\n",
    "    transformed_points <- mapply(function(x,y) tx$TransformPoint(c(x,y)), original_x_mat, original_y_mat)\n",
    "        \n",
    "    plot(original_x_mat,original_y_mat, xlim=c(-2.5,2.5), ylim=c(-2.5,2.5), pch=19, col=\"blue\", xlab=\"\", ylab=\"\", las=1)\n",
    "    points(transformed_points[1,], transformed_points[2,], col=\"red\", pch=17)\n",
    "    legend('top', col= c(\"red\", \"blue\"), pch=c(17,19), legend = c(\"transformed points\", \"original points\"))\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## BSpline\n",
    "Using a sparse set of control points to control a free form deformation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Create the transformation (when working with images it is easier to use the BSplineTransformInitializer function\n",
    "# or its object oriented counterpart BSplineTransformInitializerFilter).\n",
    "dimension <- 2\n",
    "spline_order <- 3\n",
    "direction_matrix_row_major <- c(1.0,0.0,0.0,1.0) # identity, mesh is axis aligned\n",
    "origin <- c(-1.0,-1.0)  \n",
    "domain_physical_dimensions <- c(2,2)\n",
    "\n",
    "bspline <- BSplineTransform(dimension, spline_order)\n",
    "bspline$SetTransformDomainOrigin(origin)\n",
    "bspline$SetTransformDomainDirection(direction_matrix_row_major)\n",
    "bspline$SetTransformDomainPhysicalDimensions(domain_physical_dimensions)\n",
    "bspline$SetTransformDomainMeshSize(c(4,3))\n",
    "\n",
    "# Random displacement of the control points.\n",
    "originalControlPointDisplacements <- runif(length(bspline$GetParameters()))\n",
    "bspline$SetParameters(originalControlPointDisplacements)\n",
    "\n",
    "# Apply the bspline transformation to a grid of points \n",
    "# starting the point set exactly at the origin of the bspline mesh is problematic as\n",
    "# these points are considered outside the transformation's domain,\n",
    "# remove epsilon below and see what happens.\n",
    "numSamplesX = 10\n",
    "numSamplesY = 20\n",
    "\n",
    "eps <- .Machine$double.eps\n",
    "\n",
    "coordsX <- seq(origin[1] + eps,\n",
    "               origin[1] + domain_physical_dimensions[1],\n",
    "               (domain_physical_dimensions[1]-eps)/(numSamplesX-1))\n",
    "coordsY <- seq(origin[2] + eps,\n",
    "               origin[2] + domain_physical_dimensions[2],\n",
    "               (domain_physical_dimensions[2]-eps)/(numSamplesY-1))\n",
    "# next two lines equivalent to Python's/MATLAB's meshgrid \n",
    "XX <- outer(coordsY*0, coordsX, \"+\")\n",
    "YY <- outer(coordsY, coordsX*0, \"+\")  \n",
    "\n",
    "display_displacement_scaling_effect(0.0, XX, YY, bspline, originalControlPointDisplacements)\n",
    "\n",
    "#uncomment the following line to see the effect of scaling the control point displacements \n",
    "# on our set of points (we recommend keeping the scaling in the range [-1.5,1.5] due to display bounds) \n",
    "#display_displacement_scaling_effect(0.5, XX, YY, bspline, originalControlPointDisplacements)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## DisplacementField\n",
    "\n",
    "A dense set of vectors representing the displacement inside the given domain. The most generic representation of a transformation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Create the displacement field. \n",
    "    \n",
    "# When working with images the safer thing to do is use the image based constructor,\n",
    "# DisplacementFieldTransform(my_image), all the fixed parameters will be set correctly and the displacement\n",
    "# field is initialized using the vectors stored in the image. SimpleITK requires that the image's pixel type be \n",
    "# \"sitkVectorFloat64\".\n",
    "displacement <- DisplacementFieldTransform(2)\n",
    "field_size <- c(10,20)\n",
    "field_origin <- c(-1.0,-1.0)  \n",
    "field_spacing <- c(2.0/9.0,2.0/19.0)   \n",
    "field_direction <- c(1,0,0,1) # direction cosine matrix (row major order)     \n",
    "\n",
    "# Concatenate all the information into a single list\n",
    "displacement$SetFixedParameters(c(field_size, field_origin, field_spacing, field_direction))\n",
    "# Set the interpolator, either sitkLinear which is default or nearest neighbor\n",
    "displacement$SetInterpolator(\"sitkNearestNeighbor\")\n",
    "\n",
    "originalDisplacements <- runif(length(displacement$GetParameters()))\n",
    "displacement$SetParameters(originalDisplacements)\n",
    "\n",
    "coordsX <- seq(field_origin[1],\n",
    "               field_origin[1]+(field_size[1]-1)*field_spacing[1],\n",
    "               field_spacing[1])\n",
    "coordsY <- seq(field_origin[2],\n",
    "               field_origin[2]+(field_size[2]-1)*field_spacing[2],\n",
    "               field_spacing[2])\n",
    "\n",
    "# next two lines equivalent to Python's/MATLAB's meshgrid \n",
    "XX <- outer(coordsY*0, coordsX, \"+\")\n",
    "YY <- outer(coordsY, coordsX*0, \"+\")  \n",
    "\n",
    "display_displacement_scaling_effect(0.0, XX, YY, displacement, originalDisplacements)\n",
    "\n",
    "#uncomment the following line to see the effect of scaling the control point displacements \n",
    "# on our set of points (we recommend keeping the scaling in the range [-1.5,1.5] due to display bounds) \n",
    "#display_displacement_scaling_effect(0.5, XX, YY, displacement, originalDisplacements)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "Displacement field transform created from an image. Remember that SimpleITK will clear the image you provide, as shown in the cell below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "displacement_image <- Image(c(64,64), \"sitkVectorFloat64\")\n",
    "\n",
    "# The only point that has any displacement is at physical SimpleITK index (0,0), R index (1,1)\n",
    "displacement <- c(0.5,0.5)\n",
    "# Note that SimpleITK indexing starts at zero.\n",
    "displacement_image$SetPixel(c(0,0), displacement)\n",
    "\n",
    "cat('Original displacement image size: ',point2str(displacement_image$GetSize()),\"\\n\")\n",
    "\n",
    "displacement_field_transform <- DisplacementFieldTransform(displacement_image)\n",
    "\n",
    "cat(\"After using the image to create a transform, displacement image size: \",\n",
    "    point2str(displacement_image$GetSize()), \"\\n\")\n",
    "\n",
    "# Check that the displacement field transform does what we expect.\n",
    "cat(\"Expected result: \",point2str(displacement),\n",
    "    \"\\nActual result: \", displacement_field_transform$TransformPoint(c(0,0)),\"\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Composite transform (Transform)\n",
    "\n",
    "The generic SimpleITK transform class. This class can represent both a single transformation (global, local), or a composite transformation (multiple transformations applied one after the other). This is the output typed returned by the SimpleITK registration framework. \n",
    "\n",
    "The choice of whether to use a composite transformation or compose transformations on your own has subtle differences in the registration framework.\n",
    "\n",
    "Below we represent the composite transformation $T_{affine}(T_{rigid}(x))$ in two ways: (1) use a composite transformation to contain the two; (2) combine the two into a single affine transformation. We can use both as initial transforms (SetInitialTransform) for the registration framework (ImageRegistrationMethod). The difference is that in the former case the optimized parameters belong to the rigid transformation and in the later they belong to the combined-affine transformation. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Create a composite transformation: T_affine(T_rigid(x)).\n",
    "rigid_center <- c(100,100,100)\n",
    "theta_x <- 0.0\n",
    "theta_y <- 0.0\n",
    "theta_z <- pi/2.0\n",
    "rigid_translation <- c(1,2,3)\n",
    "rigid_euler <- Euler3DTransform(rigid_center, theta_x, theta_y, theta_z, rigid_translation)\n",
    "\n",
    "affine_center <- c(20, 20, 20)\n",
    "affine_translation <- c(5,6,7)  \n",
    "\n",
    "# Matrix is represented as a vector-like data in row major order.\n",
    "affine_matrix <- runif(9)         \n",
    "affine <- AffineTransform(affine_matrix, affine_translation, affine_center)\n",
    "\n",
    "# Using the composite transformation we just add them in (stack based, first in - last applied).\n",
    "composite_transform <- Transform(affine)\n",
    "composite_transform$AddTransform(rigid_euler)\n",
    "\n",
    "# Create a single transform manually. this is a recipe for compositing any two global transformations\n",
    "# into an affine transformation, T_0(T_1(x)):\n",
    "# A = A=A0*A1\n",
    "# c = c1\n",
    "# t = A0*[t1+c1-c0] + t0+c0-c1\n",
    "A0 <- t(matrix(affine$GetMatrix(), 3, 3))\n",
    "c0 <- affine$GetCenter()\n",
    "t0 <- affine$GetTranslation()\n",
    "\n",
    "A1 <- t(matrix(rigid_euler$GetMatrix(), 3, 3))\n",
    "c1 <- rigid_euler$GetCenter()\n",
    "t1 <- rigid_euler$GetTranslation()\n",
    "\n",
    "combined_mat <- A0%*%A1\n",
    "combined_center <- c1\n",
    "combined_translation <- A0 %*% (t1+c1-c0) + t0+c0-c1\n",
    "combined_affine <- AffineTransform(c(t(combined_mat)), combined_translation, combined_center)\n",
    "\n",
    "# Check if the two transformations are \"equivalent\".\n",
    "cat(\"Apply the two transformations to the same point cloud:\\n\")\n",
    "print_transformation_differences(composite_transform, combined_affine)\n",
    "\n",
    "cat(\"\\nTransform parameters:\\n\")\n",
    "cat(paste(\"\\tComposite transform: \", point2str(composite_transform$GetParameters(),2),\"\\n\"))\n",
    "cat(paste(\"\\tCombined affine: \", point2str(combined_affine$GetParameters(),2),\"\\n\"))\n",
    "\n",
    "cat(\"Fixed parameters:\\n\")\n",
    "cat(paste(\"\\tComposite transform: \", point2str(composite_transform$GetFixedParameters(),2),\"\\n\"))\n",
    "cat(paste(\"\\tCombined affine: \", point2str(combined_affine$GetFixedParameters(),2),\"\\n\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "Composite transforms enable a combination of a global transformation with multiple local/bounded transformations. This is useful if we want to apply deformations only in regions that deform while other regions are only effected by the global transformation.\n",
    "\n",
    "The following code illustrates this, where the whole region is translated and subregions have different deformations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Global transformation.\n",
    "translation <- TranslationTransform(2, c(1.0,0.0))\n",
    "\n",
    "# Displacement in region 1.\n",
    "displacement1 <- DisplacementFieldTransform(2)\n",
    "field_size <- c(10,20)\n",
    "field_origin <- c(-1.0,-1.0)  \n",
    "field_spacing <- c(2.0/9.0,2.0/19.0)   \n",
    "field_direction <- c(1,0,0,1) # direction cosine matrix (row major order)     \n",
    "\n",
    "# Concatenate all the information into  a single list.\n",
    "displacement1$SetFixedParameters(c(field_size, field_origin, field_spacing, field_direction))\n",
    "displacement1$SetParameters(rep(1.0, length(displacement1$GetParameters())))\n",
    "\n",
    "# Displacement in region 2.\n",
    "displacement2 <- DisplacementFieldTransform(2)\n",
    "field_size <- c(10,20)\n",
    "field_origin <- c(1.0,-3)  \n",
    "field_spacing <- c(2.0/9.0,2.0/19.0)   \n",
    "field_direction <- c(1,0,0,1) #direction cosine matrix (row major order)     \n",
    "\n",
    "# Concatenate all the information into a single list.\n",
    "displacement2$SetFixedParameters(c(field_size, field_origin, field_spacing, field_direction))\n",
    "displacement2$SetParameters(rep(-1.0, length(displacement2$GetParameters())))\n",
    "\n",
    "# Composite transform which applies the global and local transformations.\n",
    "composite <- Transform(translation)\n",
    "composite$AddTransform(displacement1)\n",
    "composite$AddTransform(displacement2)\n",
    "\n",
    "# Apply the composite transformation to points in ([-1,-3],[3,1]) and \n",
    "# display the deformation using a quiver plot.\n",
    "        \n",
    "# Generate points.\n",
    "numSamplesX <- 10\n",
    "numSamplesY <- 10\n",
    "coordsX <- seq(-1.0, 3.0, 4.0/(numSamplesX-1))\n",
    "coordsY <- seq(-3.0, 1.0, 4.0/(numSamplesY-1))\n",
    "# next two lines equivalent to Python's/MATLAB's meshgrid \n",
    "original_x_mat <- outer(coordsY*0, coordsX, \"+\")\n",
    "original_y_mat <- outer(coordsY, coordsX*0, \"+\")  \n",
    "\n",
    "# Transform points and plot.\n",
    "original_points <- mapply(function(x,y) c(x,y), original_x_mat, original_y_mat)\n",
    "transformed_points <- mapply(function(x,y) composite$TransformPoint(c(x,y)), original_x_mat, original_y_mat)\n",
    "plot(0,0,xlim=c(-1.0,3.0), ylim=c(-3.0,1.0), las=1)\n",
    "arrows(original_points[1,], original_points[2,], transformed_points[1,], transformed_points[2,])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "## Writing and Reading\n",
    "\n",
    "The SimpleITK.ReadTransform() returns a SimpleITK.Transform . The content of the file can be any of the SimpleITK transformations or a composite (set of transformations). "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Create a 2D rigid transformation, write it to disk and read it back.\n",
    "basic_transform <- Euler2DTransform()\n",
    "basic_transform$SetTranslation(c(1,2))\n",
    "basic_transform$SetAngle(pi/2.0)\n",
    "\n",
    "full_file_name <- file.path(OUTPUT_DIR, \"euler2D.tfm\")\n",
    "\n",
    "WriteTransform(basic_transform, full_file_name)\n",
    "\n",
    "# The ReadTransform function returns a SimpleITK Transform no matter the type of the transform \n",
    "# found in the file (global, bounded, composite).\n",
    "read_result <- ReadTransform(full_file_name)\n",
    "cat(paste(\"Original type: \",basic_transform$GetName(),\"\\nType after reading: \", read_result$GetName(),\"\\n\"))\n",
    "print_transformation_differences(basic_transform, read_result)\n",
    "\n",
    "\n",
    "# Create a composite transform then write and read.\n",
    "displacement <- DisplacementFieldTransform(2)\n",
    "field_size <- c(10,20)\n",
    "field_origin <- c(-10.0,-100.0)  \n",
    "field_spacing <- c(20.0/(field_size[1]-1),200.0/(field_size[2]-1)) \n",
    "field_direction <- c(1,0,0,1) #direction cosine matrix (row major order)\n",
    "\n",
    "# Concatenate all the information into a single list.\n",
    "displacement$SetFixedParameters(c(field_size, field_origin, field_spacing, field_direction))\n",
    "displacement$SetParameters(runif(length(displacement$GetParameters())))\n",
    "\n",
    "composite_transform <- Transform(basic_transform)\n",
    "composite_transform$AddTransform(displacement)\n",
    "\n",
    "full_file_name <- file.path(OUTPUT_DIR, \"composite.tfm\")\n",
    "\n",
    "WriteTransform(composite_transform, full_file_name)\n",
    "read_result <- ReadTransform(full_file_name)\n",
    "cat(\"\\n\")\n",
    "print_transformation_differences(composite_transform, read_result)    "
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "R",
   "language": "R",
   "name": "ir"
  },
  "language_info": {
   "codemirror_mode": "r",
   "file_extension": ".r",
   "mimetype": "text/x-r-source",
   "name": "R",
   "pygments_lexer": "r",
   "version": "3.3.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
